package hello;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;

public class AC extends HttpServlet {
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 驱动程序名
		String driver = "com.mysql.jdbc.Driver";
		// URL指向要访问的数据库名world
		String url = "jdbc:mysql://127.0.0.1:3306/FunChat";
		// MySQL配置时的用户名
		String user = "root";
		// MySQL配置时的密码
		String password = "123";
		String name;
		try {
			// 加载驱动程序
			Class.forName(driver);
			// 连续数据库
			Connection conn = (Connection) DriverManager.getConnection(url, user, password);
			if (!conn.isClosed())
				System.out.println("Succeeded connecting to the Database!");
			// statement用来执行SQL语句
			Statement statement = (Statement) conn.createStatement();
			// 要执行的SQL语句
			String sql = "select * from city";
			// 结果集
			ResultSet rs = statement.executeQuery(sql);
			while (rs.next()) {
				// 选择Name这列数据
				name = rs.getString("Name");
				// 输出结果
				System.out.println(rs.getString("CountryCode") + "\t" + name);
			}
			rs.close();
			conn.close();
		} catch (ClassNotFoundException e) {
			System.out.println("Sorry,can`t find the Driver!");
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json; charset=utf-8");
		String jsonStr = "{\"name\":\"fly\",\"type\":\"虫子\"}";
		PrintWriter out = null;
		try {
			out = response.getWriter();
			out.write(jsonStr);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}
}
